package com.walk.zworld.view.location.amap;

import android.app.Application;
import android.app.NotificationChannel;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.app.Notification;
import android.app.NotificationManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.base.lib.base.BaseApplication;
import com.base.lib.base.utils.ToastUtil;
import com.walk.zworld.R;

import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class AMapLocationUtils {
    private static int locateTimes = 0;

    //声明AMapLocationClient类对象
    private static AMapLocationClient mLocationClient = null;
    private static AMapLocationClientOption mOption = null;

    public static boolean isBindLocation = false;
    public static boolean isSartLocation = false;

    public static void startLocation(){
        try{
            if (mLocationClient != null) {
                mLocationClient.startLocation();
                isSartLocation = true;
            } else {
                isBindLocation = false;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static void bindLocate(Context mContext, AMapLocationListener v){
        try{
            Application appContext = BaseApplication.Companion.getInstance();
            AMapLocationClient.updatePrivacyShow(appContext,true,true);
            AMapLocationClient.updatePrivacyAgree(appContext,true);
            //初始化定位
            mLocationClient = new AMapLocationClient(appContext);
            //异步获取定位结果
            AMapLocationListener mAMapLocationListener = v!=null?v: amapLocation -> {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        Log.i("高德地图调试:","amapLocation=" + amapLocation.toStr());
                        double latitude = amapLocation.getLatitude();
                        double longitude = amapLocation.getLongitude();
                        String district = amapLocation.getDistrict();
//                            Log.e("省:",amapLocation.getProvince() + "");
//                            Log.e("市:",amapLocation.getCity() + "");
//                            Log.e("区:",amapLocation.getDistrict() + "");
//                            Log.e("城市编码 + 首页:",amapLocation.getCityCode() + "");
                        //定位完成之后更新数据
//                            TextView text = (TextView) v;
//                            ((TextView) v).setText(district);
//                            CityPicker.from((FragmentActivity) mContext).locateComplete(new LocatedCity(info.getDistrict(), info.getProvince(), "101240701"), LocateState.SUCCESS);
                        //定位完成之后更新数据,去查本地db文件得到id
                        //DBManager dbManager = new DBManager(mContext);
                        //LocatedCity locatedCity = dbManager.getLocatedCity(info.getDistrict()).get(0);
//                            Log.e("测试是否获取的code","code->"+locatedCity.getCode());
//                            AppSharedPreferences.getInstance(mContext).set("district",info.getDistrict());
//                            AppSharedPreferences.getInstance(mContext).set("city",info.getCity());
//                            AppSharedPreferences.getInstance(mContext).set("code",locatedCity.getCode());
                    }else{
                        Log.e("高德地图调试:","错误码" + amapLocation.getErrorCode() + "");
                        Log.e("高德地图调试:","错误信息" + amapLocation.getErrorInfo() + "");
                        Log.e("高德地图调试:","错误描述" + amapLocation.getLocationDetail() + "");
                    }
                }else{
                    ToastUtil.showToast("定位失败 ");
                }
                //停止定位
//                    stopLocation();
            };
            //设置定位回调监听
            mLocationClient.setLocationListener(mAMapLocationListener);
            isBindLocation = true;
        }catch (Exception e){
            e.printStackTrace();
        }
    }


//----------------------------以下代码是创建后台定位通知栏的,可以不用-------------------------

    /**
     * 获取客户的
     */
    public static AMapLocationClient getClient(){
        return mLocationClient;
    }
    /**
     * 停止定位
     */
    public static void stopLocation(){
        try {
            // 停止定位
            mLocationClient.stopLocation();
            isSartLocation = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 销毁定位
     */
    public static void destroyLocation(){
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
        }
        isSartLocation = false;
    }

    public static final int NOTIFY_ID = 2001;
    private static final String NOTIFICATION_CHANNEL_NAME = "AMapBackgroundLocation";
    private static NotificationManager notificationManager = null;
    private static boolean isCreatedChannel = false;

    /**
     * 创建一个通知栏，API>=26时才有效
     * @param context
     * @return
     */
    public static Notification buildNotification(Context context) {
        try {
            Context mContext = context.getApplicationContext();
            Notification.Builder builder = null;
            Notification notification = null;
            if (android.os.Build.VERSION.SDK_INT >= 26) {
                //Android O上对Notification进行了修改，如果设置的targetSDKVersion>=26建议使用此种方式创建通知栏
                if (null == notificationManager) {
                    notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
                }
                String channelId = mContext.getPackageName();
                if (!isCreatedChannel) {
                    NotificationChannel notificationChannel = new NotificationChannel(channelId,
                            NOTIFICATION_CHANNEL_NAME,
                            NotificationManager.IMPORTANCE_DEFAULT);
                    notificationChannel.enableLights(true);//是否在桌面icon右上角展示小圆点
                    notificationChannel.setLightColor(Color.BLUE); //小圆点颜色
                    notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                    notificationManager.createNotificationChannel(notificationChannel);
                    isCreatedChannel = true;
                }
                builder = new Notification.Builder(mContext, channelId);
            } else {
                builder = new Notification.Builder(mContext);
            }
            builder.setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(getAppName(mContext))
                    .setContentText("正在后台运行")
                    .setWhen(System.currentTimeMillis());

            notification = builder.build();
            return notification;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取app的名称
     * @param context
     * @return
     */
    public static String getAppName(Context context) {
        String appName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            appName =  context.getResources().getString(labelRes);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return appName;
    }
}
